package com.songtech.utils;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 *
 */
public class BaiduUtil {

    private static  Logger logger = LoggerFactory.getLogger(BaiduUtil.class);
    private static final String BAIDU_AK = "A4LmXLHVeMzGbVYqMvC4i5tiodzwqKn5";

    public static String getCity(String lat, String lng) {
        JSONObject obj = getLocationInfo(lat, lng).getJSONObject("result").getJSONObject("addressComponent");
        return obj.getString("city");
    }

    public static JSONObject getLocationInfo(String lat, String lng) {
        String url = "http://api.map.baidu.com/geocoder/v2/?location=" + lat
                + "," + lng + "&output=json&ak="+BAIDU_AK+"&pois=0";
        JSONObject obj = JSONObject.parseObject(HttpUtil.getRequest(url));
        return obj;

    }

    public static String getAddress(String lng, String lat) {  //lng经度，lat纬度
        JSONObject obj = getLocationInfo(lat, lng).getJSONObject("result");
        StringBuilder address = new StringBuilder();
        String province = obj.getJSONObject("addressComponent").getString("province");
        String city = obj.getJSONObject("addressComponent").getString("city");
        //直辖市的省份名称和城市名称一样，判断重复时去掉
        if (province != null && city != null && province.equals(city)) {
            address.append(
                    obj.getJSONObject("addressComponent").getString("city"))
                    .append(obj.getJSONObject("addressComponent").getString("district"))
                    .append(obj.getJSONObject("addressComponent").getString("street"))
                    .append(obj.getString("sematic_description"));
        } else {
            address.append(
                    obj.getJSONObject("addressComponent").getString("province"))
                    .append(obj.getJSONObject("addressComponent").getString("city"))
                    .append(obj.getJSONObject("addressComponent").getString("district"))
                    .append(obj.getJSONObject("addressComponent").getString("street"))
                    .append(obj.getString("sematic_description"));
        }
        return address.toString();
    }

    public static void main(String[] args) {
        System.out.println("\n"+"经纬度具体地址为："
                + BaiduUtil.getAddress("106.49145","29.62161"));
    }


}